Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void freeMem(char **names, int size);
float txFam(int size, float ageSum, char **names);
int main()
{
int fam_size=0;
float sumAge=0;
float aveAge=0.0;
int i=0;
int j=0;
int k=0;
char ch;
/* generate array of strings the size of family */
printf("How large is your Family: ");
scanf("%d", &fam_size);
ch = getchar();
/* Allocate memory for 2d-array of strings */
char **namesTx=malloc(fam_size*sizeof(char *));
/* txFam returns sumAge to calculate aveAge */
sumAge = txFam(fam_size, sumAge, namesTx);
aveAge = (sumAge/fam_size);
printf("The average age of the family is %.2f", aveAge);
printf("\nFamily Members from Texas are: ");
for(j=0; j<fam_size; j++)
printf("\n%s", namesTx[j]);
freeMem(namesTx, fam_size);
getchar();
}
void freeMem(char **names, int size)
{
for(int k=0; k<size; k++) free(names[k]);
free(names);
}
void printFam(char **names, int size)
{
}
float txFam(int size, float ageSum, char **names)
{
int txCnt=0;
float Age=0;
char state[4];
char tempName[20];
int cmp=0;
for(int k=0; k<size; k++){
names[k]=malloc(20*sizeof(char *));
}
for(int i=0; i<size; i++){
printf("\nEnter your family member's name: ");
fgets(tempName, 20, stdin);
printf("\nWhat state is s/he from? (use postal abbr) ");
fgets(state, 4, stdin);
printf("\nHow old? ");
scanf("%f", &Age);
ageSum += Age;
getchar();
getchar();
/* saves names of family members from TX only */
state[strlen(state)-1]="\0";
cmp = strcmp(state,"TX");
if( cmp == 0 ){
strcpy(names[txCnt], tempName);
txCnt++;
}
}
return ageSum;
}
I am getting this message now:
joshuarayfp.c: In function 'txFam':
joshuarayfp.c:74:31: warning: assignment makes integer from pointer without a cast
state[strlen(state)-1]="\0";
Any ideas?
![Quote](https://cboard.cprogramming.com/images/misc/quote_icon.png)
Originally Posted by
camel-man
Strcmp works as so
"This function return values that are as follows:
if Return value < 0 then it indicates str1 is less than str2.
if Return value > 0 then it indicates str2 is less than str1.
if Return value = 0 then it indicates str1 is equal to str2
"
Meaning that the number it returns whether it's 10 or 230000, it doesn't matter it is indicating that they are not equal. You need to worry about checking to see if they're equal. The only time it will return 0 is when the two strings are equal. You need to trim the newline character off of State, or add in a newline character when comparing your "TX\n".
A quick easy way to trim the newline is
Code:
state[strlen(state) - 1] = '\0';
Then you can continue to compare as normal with ==0